package com.godenwater.recv.decode;

import com.godenwater.recv.model.CommonMessage;
import com.godenwater.recv.server.yln.YlnMessageHeader;
import org.apache.mina.core.buffer.IoBuffer;

/**
 * 燕禹协议解析器
 * 
 * @author admin
 *
 */
public class YlnMessageDecoder {

	public static CommonMessage decode( byte[] buffer) {
		// 燕禹协议
		YlnMessageHeader header = new YlnMessageHeader();

		int pos = 1;

		// 上行的，中心站地址在前
		byte[] startBit = new byte[header.getLenStartBit()];
		System.arraycopy(buffer, pos, startBit, 0, startBit.length);
		header.setSTART_BIT(startBit);
		pos = pos + header.getLenStartBit();

		int bodyLen = buffer.length - 4;
		byte[] content = new byte[bodyLen];
		System.arraycopy(buffer, pos, content, 0, bodyLen);

		// --------------------------------
		CommonMessage temp = new CommonMessage();
		temp.setHeader(header);
		temp.setCrclen(0);
		temp.setBodySize(buffer.length - 3);// 需要减去三个字节，一位结束符，两位CRC校验符
		temp.setContent(content);
		temp.setEOF((byte)0x00);
		temp.setCRC(null);
		return temp;
	}

	public static CommonMessage decode(byte[] ylnHeader,IoBuffer buffer) {
		//亿立能协议
		int contentLen = buffer.remaining();

		// --------------------------------
		YlnMessageHeader header = new YlnMessageHeader();
		header.setSTART_BIT(ylnHeader);

		CommonMessage message = new CommonMessage();
		message.setHeader(header);
		message.setCrclen(0);
		message.setBodySize(buffer.remaining());// 需要减去三个字节，一位结束符，两位CRC校验符

		if(contentLen > 1) {
			byte[] content = new byte[contentLen ];
			buffer.get(content);
			message.setContents(content);
		}
		message.setEOF((byte)0x00);
		message.setCRC(null);

		return message;
	}

}
